package com.wzx.ptplatform.controller;

import com.wzx.ptplatform.utils.MapUtils;
import io.swagger.annotations.Api;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @author 紫煦桉
 */
@Api(tags = "上传模块")
@RestController
public class UploadController {

    static final String PATH = System.getProperty("user.dir");
    static final String UPLOAD_PATH = "\\src\\main\\resources\\static\\ptplatform\\upload\\images";

    public static final String IMAGES_PATH = PATH + UPLOAD_PATH;

    public static void main(String[] args) {
        System.out.println(IMAGES_PATH);
    }

    @PostMapping("upload_images")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file, Model model) {
        Map<String, Object> map = MapUtils.initializeMap();
        if (file.isEmpty()) {
            return map;
        }
        String fileName = file.getOriginalFilename();
        // 取出上传文件的后缀/类型
        assert fileName != null;
        String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 随机生成一个新的文件名
        String uuid = UUID.randomUUID().toString();
        String newFileName = uuid + "." + extName;
        File dest = new File(IMAGES_PATH + "/" + newFileName);
        System.out.println(dest.getAbsolutePath());
        try {
            file.transferTo(dest);
            model.addAttribute("imageFile", "images/" + newFileName);
            MapUtils.successMap(map);
            map.put("src", "upload/images/" + newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
